package com.example.base_kotlin_xml.model

import androidx.lifecycle.viewModelScope
import com.example.base_model.mvvm.BaseViewModel
import com.example.base_model.network.load.LoadingStrategy
import com.example.base_model.network.load.LoadingUiState
import com.example.base_model.network.request_param.BeanParamInterface
import com.example.base_model.network.request_param.MapParamInterface
import com.example.base_model.network.result.BaseResult
import com.example.base_model.room.bean.User
import com.example.base_model.room.dao.UserDao
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject

/**
 * @Author jiangKunKun
 * @CreateDate 2025/7/31
 * @Description
 * @SpittingGrooves
 */
data class RoomUiState(
    override val loadingGroups: Map<LoadingStrategy, Int> = emptyMap(),
    val addUserResult: BaseResult<Long> = BaseResult.IDLE(),
    val updateUserResult: BaseResult<Int> = BaseResult.IDLE(),
    val deleteUserResult: BaseResult<Int> = BaseResult.IDLE(),
    val selectUserResult: BaseResult<User?> = BaseResult.IDLE(),
    val selectAllUserResult: BaseResult<List<User>> = BaseResult.IDLE(),
    val deleteAllUserResult: BaseResult<Int> = BaseResult.IDLE()
) : LoadingUiState {
    override fun copyWithLoading(groups: Map<LoadingStrategy, Int>): LoadingUiState {
        return this.copy(loadingGroups = groups)
    }
}
@HiltViewModel
class RoomViewModel @Inject constructor(
    private val userDao: UserDao
): BaseViewModel() {
    // 转换为 StateFlow (它有初始值，且是热流，UI 更易于处理) 实时监听数据库的变化
    val allUsersStateFlow: StateFlow<List<User>> = userDao.getAllUsersFlow()
        .stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000), // Flow 在最后一个订阅者消失5秒后停止
            initialValue = emptyList() // 提供一个初始值
        )

    // 2. 使用统一的 StateFlow
    private val _uiState = MutableStateFlow(RoomUiState())
    val uiState: StateFlow<RoomUiState> = _uiState.asStateFlow()
    fun addUser(name: String, email: String?) {
        val user = User(name = name, email = email)
        launchLocWithStateFlow(
            stateFlow = _uiState,
            loadingStrategy = LoadingStrategy.MAIN, // 可以指定加载策略
            stateUpdateBlock = { state, result -> state.copy(addUserResult = result) },
            block = { userDao.insertUser(user) },
            requestParam = BeanParamInterface(user)
        )
    }

    fun updateUser(user: User) {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { state, result -> state.copy(updateUserResult = result) },
            block = { userDao.updateUser(user) },
            requestParam = BeanParamInterface(user)
        )
    }

    fun getUserById(userId: Int) {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { state, result -> state.copy(selectUserResult = result) },
            block = { userDao.getUserById(userId) },
            requestParam = MapParamInterface(mapOf("userId" to userId))
        )
    }

    // 删除一个
    fun deleteUser(userId: Int) {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { state, result -> state.copy(deleteUserResult = result) },
            block = {
                userDao.deleteUserById(userId)
            }, requestParam = BeanParamInterface(mapOf("userId" to userId))
        )
    }

    // 查询全部
    fun getUserAll() {
        launchLocWithStateFlow(
            stateFlow =  _uiState ,
            stateUpdateBlock = { state, result -> state.copy(selectAllUserResult = result) },
            block = {
                userDao.getAllUsers()
            },
            transform = {
                it.apply {
                    it.forEach { item ->
                        item.name =  "${item.name}  修改后的名字 foxABC"
                    }
                }
            }
        )
    }

    // 删除全部
    fun deleteAllUsers() {
        launchLocWithStateFlow(
            stateFlow = _uiState,
            stateUpdateBlock = { state, result -> state.copy(deleteAllUserResult = result) },
            block = {
                userDao.deleteAllUsers()
            }
        )
    }
}